/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

package com.iti.jets.gpts.service;


import com.iti.jets.gpts.pojo.User;
import com.sun.jersey.api.client.Client;
import com.sun.jersey.api.client.UniformInterfaceException;
import com.sun.jersey.api.client.WebResource;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
import javax.faces.model.DataModel;
import javax.faces.model.ListDataModel;
import org.codehaus.jettison.json.JSONArray;
import org.codehaus.jettison.json.JSONException;
import org.codehaus.jettison.json.JSONObject;




/**
 *
 * @author YASMIN-ITI
 */

public class UserService {
    
    
    private WebResource webResource;
    private Client client;
    private static final String BASE_URI = "http://localhost:48651/GPTRP/rest";
    
    public UserService() {
        com.sun.jersey.api.client.config.ClientConfig config = new com.sun.jersey.api.client.config.DefaultClientConfig();
        client = Client.create(config);
        webResource = client.resource(BASE_URI).path("user");
        getAllUser();
       
    }

    public List<User> getAllUser() throws UniformInterfaceException {
        
        WebResource resource = webResource;
        resource = resource.path("getalluser");
        JSONArray array = resource.accept(javax.ws.rs.core.MediaType.APPLICATION_JSON).get(JSONArray.class);
        List<User> users = new ArrayList<User>();
        for(int i = 0; i < array.length(); i++)
        {
            JSONObject jSONObject;
            try {
                jSONObject = array.getJSONObject(i);
                User user = new User();
                user.setId(jSONObject.getInt("id"));
                user.setEmail(jSONObject.getString("email"));
               
                users.add(user);
                
            } catch (JSONException ex) {
                ex.printStackTrace();
            }
        }
        return users;
    }
    public void removeUser(int id) {
        WebResource resource = webResource;
        resource = resource.path("/removeuser");
       resource.path("/" + id).get(String.class);  
    }
    public void close() {
        client.destroy();
    }

   
    
}